package org.timeismoney.payment.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.timeismoney.payment.common.Constants;
import org.timeismoney.payment.exception.BizException;
import org.timeismoney.payment.model.Student;
import org.timeismoney.payment.model.Teacher;
import org.timeismoney.payment.service.UnitLevelService;

public class AuthorizationFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpSession session = ((HttpServletRequest) arg0).getSession();
		WebApplicationContext context = WebApplicationContextUtils
				.getWebApplicationContext(session.getServletContext());
		try {
			checkAuth((HttpServletRequest) arg0, context);
		} catch (BizException e) {
			if (!isAjaxRequest(arg0)) {
				arg0.setAttribute("error", e.getMessage());
				arg0.getRequestDispatcher("/").forward(arg0, arg1);
			}else{
				arg1.setCharacterEncoding("utf-8");
				arg1.setContentType("text/x-json;charset=utf-8");
				arg1.getOutputStream().write(WebUtils.generateErrorJSON(e.getMessage()).getBytes("utf-8"));
			}
			return;
		}

		// init units level
		if (session.getAttribute(Constants.ATTR_KEY_UNIT_LEVELS) == null) {
			initUnitLevels(context, session);
		}

		arg2.doFilter(arg0, arg1);

	}

	private void checkAuth(HttpServletRequest req, WebApplicationContext context)
			throws ServletException {
		Object obj = req.getSession().getAttribute(Constants.USER_IN_SESSION);
		if (obj == null) {
			throw new BizException("操作超时，请重新登录！");
		}
		String path = req.getServletPath();
		boolean auth = true;
		if (obj instanceof Student) {
			if (path != null && path.contains("/teacher")) {
				auth = false;
			}
		} else if (obj instanceof Teacher) {
			if (path != null && path.contains("/student")) {
				auth = false;
			}
		}
		if (!auth) {
			throw new BizException("未授权操作！");
		}
	}

	private void initUnitLevels(WebApplicationContext context,
			HttpSession session) {
		UnitLevelService levelService = (UnitLevelService) context
				.getBean("unitLevelService");
		session.setAttribute(Constants.ATTR_KEY_UNIT_LEVELS,
				levelService.getAll());
	}
	
	private boolean isAjaxRequest(ServletRequest req){
		String ajax = req.getParameter("ajax");
		return "ajax".equals(ajax);
	}

	public void init(FilterConfig arg0) throws ServletException {
	}

}
